package com.evil.common.util;

import com.alibaba.fastjson.JSONException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 阿巳
 */
@Slf4j
public class JSONUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    static{
        MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    }

    /**
     * 将对象转换为json
     * @param object 对象信息
     * @return json串
     * @throws JsonProcessingException
     */
    public static String encodeJSON(Object object){
        try {
            return MAPPER.writeValueAsString(object);
        }catch (JsonProcessingException e){
            throw new JSONException("对象转换JSON异常：{}",e);
        }
    }

    /**
     * json串转为对象信息
     * @param json 串
     * @param type 类型
     * @param <T> 泛型
     * @return 对象
     */
    public static <T> T decodeJSON(String json,Class<T> type){
        try {
            return MAPPER.readValue(json,type);
        }catch (Exception e){
            throw new JSONException("json串解码异常：{}",e);
        }
    }
}
